<template>
  <view class="container">
    <!-- 列表视图：展示已设置的本地定时 -->
    <view v-if="view === 'list'" class="list-view">
      <view
        v-for="(it, idx) in items"
        :key="idx"
        class="item-card"
        @click="edit(idx)"
      >
        <view class="item-head">
          <text class="time-text"
            >{{ formatTime(it) }}
            {{ formatRepeat(it.repeatType, it.customDays) }}</text
          >
          <u-switch v-model="it.enable" />
        </view>
        <view class="item-desc">{{ formatActions(it.actions) }}</view>
      </view>

      <view class="list-actions">
        <!-- <u-button type="success" class="edit-btn" @click="edit(0)"
          >编辑</u-button
        > -->
        <u-button type="primary" class="add-btn" @click="addNew" block>添加</u-button>
      </view>
    </view>

    <!-- 编辑视图：设置时间、重复、动作 -->
    <view v-else-if="view === 'edit'" class="edit-view">
      <view class="card">
        <picker-view
          class="picker"
          indicator-style="height: 40px;"
          :value="pickerValue"
          @change="onPickerChange"
        >
          <picker-view-column>
            <view v-for="ap in ampmList" :key="ap" class="picker-item">{{
              ap
            }}</view>
          </picker-view-column>
          <picker-view-column>
            <view v-for="h in hourList" :key="h" class="picker-item">{{
              h
            }}</view>
          </picker-view-column>
          <picker-view-column>
            <view v-for="m in minuteList" :key="m" class="picker-item">{{
              pad(m)
            }}</view>
          </picker-view-column>
        </picker-view>
      </view>

      <view class="card" @click="openRepeat">
        <u-cell-group>
          <u-cell
            title="重复"
            :value="formatRepeat(editForm.repeatType, editForm.customDays)"
            isLink
          />
        </u-cell-group>
      </view>

      <view class="card">
        <u-cell-group>
          <u-cell
            v-for="i in 4"
            :key="i"
            :title="`开关${i}`"
            :value="editForm.actions[i] ? editForm.actions[i] : ''"
            isLink
            @click="openAction(i)"
          >
            <template #right-icon>
              <u-icon name="plus" size="20" color="#60a4f7" />
            </template>
          </u-cell>
        </u-cell-group>
      </view>

      <u-button type="primary" class="save-btn" @click="save">保存</u-button>
    </view>

    <!-- 重复视图 -->
    <view v-else-if="view === 'repeat'" class="repeat-view">
      <u-radio-group v-model="repeatTemp" placement="column">
        <u-radio label="执行一次" name="once" />
        <u-radio label="每天" name="everyday" />
        <u-radio label="工作日" name="workday" />
        <u-radio label="周末" name="weekend" />
        <u-radio label="自定义" name="custom" />
      </u-radio-group>
      <u-button type="primary" class="save-btn" @click="saveRepeat"
        >保存</u-button
      >
    </view>

    <!-- 自定义周选择视图 -->
    <view v-else-if="view === 'custom'" class="custom-view">
      <view class="week-list">
        <view
          v-for="d in weekDays"
          :key="d.value"
          class="week-item"
          @click="toggleDay(d.value)"
        >
          <text>{{ d.label }}</text>
          <u-icon
            :name="customDaysTemp.includes(d.value) ? 'checkmark' : 'circle'"
            :color="customDaysTemp.includes(d.value) ? '#60a4f7' : '#c0c4cc'"
          />
        </view>
      </view>
      <u-button type="primary" class="save-btn" @click="saveCustomDays"
        >保存</u-button
      >
    </view>

    <!-- 开关动作设置弹窗 -->
    <u-popup
      :show="actionPopup"
      mode="bottom"
      :round="10"
      @close="actionPopup = false"
    >
      <view class="action-sheet">
        <view class="sheet-head">
          <text>开关{{ currentActionIndex }}</text>
          <text class="delete" @click="deleteAction">删除</text>
        </view>
        <u-radio-group v-model="actionTemp" placement="column">
          <u-radio label="关" name="关" />
          <u-radio label="开" name="开" />
        </u-radio-group>
        <view class="sheet-actions">
          <u-button class="cancel-btn" plain @click="actionPopup = false"
            >取消</u-button
          >
          <u-button type="primary" class="ok-btn" @click="confirmAction"
            >确定</u-button
          >
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      view: "list",
      items: [
        {
          ampm: "下午",
          hour: 3,
          minute: 32,
          repeatType: "once",
          customDays: [],
          actions: { 1: "关" },
          enable: true,
        },
      ],
      editingIndex: null,
      editForm: {
        ampm: "上午",
        hour: 12,
        minute: 0,
        repeatType: "everyday",
        customDays: [],
        actions: { 1: null, 2: null, 3: null, 4: null },
      },

      ampmList: ["上午", "下午"],
      hourList: Array.from({ length: 12 }, (_, i) => i + 1),
      minuteList: Array.from({ length: 60 }, (_, i) => i),

      repeatTemp: "everyday",
      weekDays: [
        { label: "周一", value: 1 },
        { label: "周二", value: 2 },
        { label: "周三", value: 3 },
        { label: "周四", value: 4 },
        { label: "周五", value: 5 },
        { label: "周六", value: 6 },
        { label: "周日", value: 7 },
      ],
      customDaysTemp: [],

      actionPopup: false,
      currentActionIndex: 1,
      actionTemp: "关",
    };
  },
  computed: {
    pickerValue() {
      return [
        this.ampmList.indexOf(this.editForm.ampm),
        this.hourList.indexOf(this.editForm.hour),
        this.editForm.minute,
      ];
    },
  },
  methods: {
    // 列表格式化
    formatTime(it) {
      return `${it.ampm === "上午" ? "" : ""}${this.pad(it.hour)}:${this.pad(
        it.minute
      )}`;
    },
    formatRepeat(type, days = []) {
      const map = {
        once: "执行一次",
        everyday: "每天",
        workday: "工作日",
        weekend: "周末",
        custom: "自定义",
      };
      if (type === "custom" && days.length) return "自定义";
      return map[type] || "每天";
    },
    formatActions(actions) {
      const arr = Object.keys(actions)
        .filter((k) => actions[k])
        .map((k) => `开关${k} ${actions[k]}`);
      return arr.join("、") || "未设置动作";
    },
    pad(n) {
      return String(n).padStart(2, "0");
    },

    // 进入编辑
    edit(idx) {
      this.editingIndex = idx;
      const it = this.items[idx] || {
        ampm: "上午",
        hour: 12,
        minute: 0,
        repeatType: "everyday",
        customDays: [],
        actions: { 1: null, 2: null, 3: null, 4: null },
      };
      this.editForm = JSON.parse(JSON.stringify(it));
      this.repeatTemp = this.editForm.repeatType;
      this.customDaysTemp = [...this.editForm.customDays];
      this.view = "edit";
    },
    addNew() {
      this.editingIndex = null;
      this.editForm = {
        ampm: "上午",
        hour: 12,
        minute: 0,
        repeatType: "everyday",
        customDays: [],
        actions: { 1: null, 2: null, 3: null, 4: null },
      };
      this.view = "edit";
    },

    // 时间选择器
    onPickerChange(e) {
      const [apIdx, hIdx, m] = e.detail.value;
      this.editForm.ampm = this.ampmList[apIdx];
      this.editForm.hour = this.hourList[hIdx];
      this.editForm.minute = m;
    },

    // 重复设置
    openRepeat() {
      this.view = "repeat";
    },
    saveRepeat() {
      if (this.repeatTemp === "custom") {
        this.view = "custom";
        return;
      }
      this.editForm.repeatType = this.repeatTemp;
      this.view = "edit";
    },
    toggleDay(v) {
      const i = this.customDaysTemp.indexOf(v);
      if (i > -1) this.customDaysTemp.splice(i, 1);
      else this.customDaysTemp.push(v);
    },
    saveCustomDays() {
      this.editForm.repeatType = "custom";
      this.editForm.customDays = [...this.customDaysTemp];
      this.view = "edit";
    },

    // 开关动作
    openAction(i) {
      this.currentActionIndex = i;
      this.actionTemp = this.editForm.actions[i] || "关";
      this.actionPopup = true;
    },
    deleteAction() {
      this.$set(this.editForm.actions, this.currentActionIndex, null);
      this.actionPopup = false;
    },
    confirmAction() {
      this.$set(
        this.editForm.actions,
        this.currentActionIndex,
        this.actionTemp
      );
      this.actionPopup = false;
    },

    // 保存
    save() {
      const payload = JSON.parse(JSON.stringify(this.editForm));
      if (this.editingIndex == null) this.items.push(payload);
      else this.items.splice(this.editingIndex, 1, payload);
      uni.showToast({ title: "已保存本地定时", icon: "none" });
      this.view = "list";
    },
  },
};
</script>

<style lang="scss" scoped>
page {
  height: 100%;
}
.container {
  height: 100%;
  background: #f6f7fb;
  padding: 16rpx;
}

.list-view .item-card {
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
}
.item-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.time-text {
  font-size: 26rpx;
  color: #1e1f23;
}
.item-desc {
  margin-top: 8rpx;
  color: #8b8d93;
  font-size: 22rpx;
}
.list-actions {
  // display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16rpx;
  margin-top: 40rpx;
}
.edit-btn,
.add-btn {
  height: 88rpx;
  border-radius: 44rpx;
}

.card {
  background: #fff;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
  margin-bottom: 16rpx;
}
.picker {
  height: 260rpx;
}
.picker-item {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.save-btn {
  margin: 40rpx 20rpx;
  border-radius: 44rpx;
}

.week-list {
  background: #fff;
  border-radius: 12rpx;
  padding: 8rpx;
}
.week-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  border-bottom: 1px solid #f0f2f5;
}
.week-item:last-child {
  border-bottom: 0;
}

.action-sheet {
  padding: 20rpx;
}
.sheet-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12rpx;
}
.delete {
  color: #ff4d4f;
}
.sheet-actions {
  display: flex;
  gap: 16rpx;
  margin-top: 20rpx;
}
.cancel-btn {
  flex: 1;
}
.ok-btn {
  flex: 1;
}
</style>
